package com.qiao.dfw.manager;

import com.qiao.dfw.config.SpringBeanUtil;
import com.qiao.dfw.dao.PlayerMapper;
import com.qiao.dfw.entity.Player;
import com.qiao.dfw.entity.PlayerLocal;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 乔占江 qq:59663479
 * @version 1.0
 * @date 2024/1/18 6:46
 * @description
 */
public class PlayerManager {
    // 缓存 账号数据
    private static final Map<String, Player> Players = new ConcurrentHashMap<>();
    // 缓存空 账号
    private static final Set<String> nullSet = new HashSet<>();

    public static void add(Player player) {
        nullSet.remove(player.username);
        if(!Players.containsKey(player.username)){
            Players.put(player.username, player);
            PlayerMapper bean = SpringBeanUtil.getBean(PlayerMapper.class);
            bean.add(player);
        }
    }

    public static Player get(String username) {
        if (nullSet.contains(username)) {
            return null;
        }

        if (!Players.containsKey(username)) {
            PlayerMapper bean = SpringBeanUtil.getBean(PlayerMapper.class);
            Player player = bean.getPlayerByName(username);
            if (player == null) {
                nullSet.add(username);
                return null;
            } else {
                Players.put(username, player);
                player.local = PlayerLocal.Non;
                return player;
            }
        } else {
            return Players.get(username);
        }
    }


}
